
\documentclass{beamer}


\mode<presentation>
{
  \usetheme{CambridgeUS}
	\usecolortheme{beaver}
  % or ...

  \setbeamercovered{transparent}
  % or whatever (possibly just delete it)
}


\usepackage{xeCJK}
\usepackage[english]{babel}
\usepackage[utf8]{inputenc}
\usepackage{times}
\usepackage[T1]{fontenc}
\usepackage{hyperref}
\usepackage{pifont}
\usepackage{bibentry}
\usepackage{verbatim}
\usepackage{color}
\newcommand{\cmark}{\ding{51}}%
\newcommand{\xmark}{\ding{55}}%
\setCJKmainfont{WenQuanYi Micro Hei}
\renewcommand{\raggedright}{\leftskip=0pt \rightskip=0pt plus 0cm}
\raggedright

\let\oldfootnotesize\footnotesize
\renewcommand*{\footnotesize}{\oldfootnotesize\tiny}


\title[MongoDB讲义] 
{MongoDB讲义}
\subtitle{介绍与快速上手}

\author[Zhilei Ren] 
{Zhilei Ren}

\institute[OSCAR Team] % (optional, but mostly needed)
{
\\\includegraphics[width=0.2\textwidth]{../utils/logo.jpg}\\
OSCAR Team, School of Software, 
Dalian University of Technology
}


\subject{MongoDB}



\pgfdeclareimage[height=0.5cm]{university-logo}{../utils/logo.jpg}
\logo{\pgfuseimage{university-logo}}



% Delete this, if you do not want the table of contents to pop up at
% the beginning of each subsection:
\AtBeginSubsection[]
{
  \begin{frame}<beamer>{Outline}
    \tableofcontents[currentsection,currentsubsection]
  \end{frame}
}


% If you wish to uncover everything in a step-wise fashion, uncomment
% the following command: 

%\beamerdefaultoverlayspecification{<+->}

\setbeamertemplate{section in toc}[circle]
\setbeamertemplate{items}[circle]
\setbeamertemplate{caption}[numbered]
\setbeamertemplate{bibliography item}{\insertbiblabel}
\setbeamertemplate{bibliography entry title}{}
\setbeamertemplate{bibliography entry journal}{}

\begin{document}

\begin{frame}
  \titlepage
\end{frame}

%\begin{frame}{Outline}
%  \tableofcontents[currentsection,currentsubsection, 
%    hideothersubsections, 
%    sectionstyle=show,
%]
%\end{frame}

\AtBeginSection[]
{
 \begin{frame}<beamer>
 \frametitle{Outline}
 \tableofcontents[currentsection]
 \end{frame}
}
\section{MongoDB简介}
\begin{frame}[t]{NoSQL简介}
    \begin{block}{概念}
        NoSQL是对不同于传统的关系数据库的数据库管理系统的统称。两者存在许多显著的不同点，其中最重要的是NoSQL不使用SQL作为查询语言。其数据存储可以不需要固定的表格模式，也经常会避免使用SQL的JOIN操作，一般有水平可扩展性的特征。

        NoSQL的结构通常提供弱一致性的保证，如最终一致性，或交易仅限于单个的数据项。

        \begin{itemize}
            \item 图形关系存储：Neo4J、ArangoDB
            \item 键-值存储：Redis、MemcacheD、BerkeleyDB
            \item 列存储: HBase、Cassandra
            \item 文档存储: MongoDB、CouchDB
        \end{itemize}
    \end{block}
\end{frame}
\begin{frame}[t]{MongoDB简介}
	\centering
	\includegraphics[width=.4\textwidth]{mongodb.png}
	\begin{block}{Intro}
		\small
		MongoDB是一种文档导向的数据库管理系统，由C++撰写而成，以此来解决应用程序开发社区中的大量现实问题。2007年10月，MongoDB由10gen团队所发展。2009年2月首度推出\footnote{\url{https://zh.wikipedia.org/zh-cn/MongoDB}}。
	\end{block}

	\Huge
	{\color{red}Mongo} for \pause hu{\color{red}mongo}us
\end{frame}
\section{MongoDB安装}
\begin{frame}[t,fragile]{MongoDB安装}
\begin{block}{开箱即用}
	\begin{itemize}
		\item Debian/Ubuntu: \begin{verbatim}sudo apt-get install mongodb\end{verbatim}
		\item Windows: \url{https://www.mongodb.com/download-center}，下载后一路Next安装，或直接下载压缩包解压
		\item OSX: \begin{verbatim}brew install mongodb\end{verbatim}
	\end{itemize}
\end{block}
\end{frame}
\begin{frame}[t]{MongoDB启动}
\begin{block}{开箱即用}
	\begin{itemize}
		\item Debian/Ubuntu: service mongodb start
		\item Windows: mongod -{}-dbpath path$\backslash$to$\backslash$dbpath
		\item OSX: mongod -{}-dbpath path/to/dbpath
	\end{itemize}
\end{block}
\end{frame}
\begin{frame}[t]{MongoDB常用参数}
	\scriptsize
	\begin{tabular}{ll}
-{}-dbpath arg  & directory for datafiles - defaults to /data/db                                \\
-{}-port arg    & specify port number - 27017 by default                                        \\
-{}-replSet arg & arg is <setname>                                                              \\
-{}-configsvr   & declare this is a config db of a cluster;                                     \\
                & default port 27019; default dir /data/configdb                                \\
-{}-journal     & enable journaling                                                             \\
-{}-nojournal   & disable journaling (journaling is on by default for 64 bit)                   \\
-{}-logpath arg & log file to send write to instead of stdout - has to be a file, not directory \\
	\end{tabular}
\end{frame}
\section{MongoDB基本操作}
\begin{frame}[t]{MongoDB REPL}
	\begin{block}{REPL}
		\small
		\begin{itemize}
			\item Read Evaluate Print Loop
			\item 在现代语言中非常流行
			\item MongoDB的REPL基于JavaScript
		\end{itemize}
	\end{block}
	\centering
	\begin{figure}
		\includegraphics[width=.4\textwidth]{definitive-vs-good.jpg}
		\caption{JavaScript: the definitive guide vs. the good parts}
	\end{figure}
\end{frame}
\begin{frame}[t]{JavaScript}
    \begin{block}{今天就能开始用的小知识}
        \begin{itemize}
            \item JavaScript学名ECMAScript
            \item JavaScript与Java的关系约等于济科和张继科的关系
            \item 相比于Java，更接近Lisp/Scheme
            \item 设计周期为10天\footnote{\url{https://www.w3.org/community/webed/wiki/A\_Short\_History\_of\_JavaScript}}\footnote{\url{https://www.bilibili.com/video/av1623152/}}\footnote{\url{https://www.destroyallsoftware.com/talks/the-birth-and-death-of-javascript}}\footnote{\url{https://gist.github.com/zhangchn/29015a7f65ce11c94846}}
        \end{itemize}
    \end{block}
\end{frame}
\begin{frame}[t]{MongoDB数据结构}
    \begin{block}{JSON}
    JSON(JavaScript Object Notation, JS 对象标记) 是一种轻量级的数据交换格式。它基于 ECMAScript (w3c制定的js规范)的一个子集，采用完全独立于编程语言的文本格式来存储和表示数据。简洁和清晰的层次结构使得 JSON 成为理想的数据交换语言。 易于人阅读和编写，同时也易于机器解析和生成，并有效地提升网络传输效率。
    \end{block}
    \begin{block}{BSON}
        BSON( Binary Serialized Document Format) 是一种二进制形式的存储格式，采用了类似于 C 语言结构体的名称、对表示方法，支持内嵌的文档对象和数组对象，具有轻量性、可遍历性、高效性的特点，可以有效描述非结构化数据和结构化数据。
    \end{block}
\end{frame}
\begin{frame}[fragile]{Example of JSON\footnote{\url{https://en.wikipedia.org/wiki/JSON}}}
    \tiny
    \begin{verbatim}
{
  "firstName": "John",
  "lastName": "Smith",
  "isAlive": true,
  "age": 25,
  "address": {
    "streetAddress": "21 2nd Street",
    "city": "New York",
    "state": "NY",
    "postalCode": "10021-3100"
  },
  "phoneNumbers": [
    {
      "type": "home",
      "number": "212 555-1234"
    },
    {
      "type": "office",
      "number": "646 555-4567"
    },
    {
      "type": "mobile",
      "number": "123 456-7890"
    }
  ],
  "children": [],
  "spouse": null
}
\end{verbatim}
\end{frame}
\begin{frame}[t,fragile]{CRUD操作概览}
\begin{block}{CRUD (1): Create}
	\scriptsize
\begin{verbatim}
#choose db
>use test
#insert json object into collection
>db.students.insert({"id": 123, "name": "zhangsan", "age": 19})
WriteResult({ "nInserted" : 1 })
\end{verbatim}
\end{block}
\begin{block}{CRUD (2): Retrieve}
	\scriptsize
\begin{verbatim}
#choose db
>use test
> db.students.find({"id": 123})
{ "_id" : ObjectId("..."), "id" : 123, "name" : "zhangsan", "age" : 19 }

\end{verbatim}
\end{block}
\end{frame}
\begin{frame}[t,fragile]{CRUD操作概览}
\begin{block}{CRUD (3): Update}
	\scriptsize
\begin{verbatim}
> db.students.update({"id":123}, {"$inc": {"age":1}})
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
> db.students.find()
{ "_id" : ObjectId("..."), "id" : 123, "name" : "zhangsan", "age" : 20 }
\end{verbatim}
\end{block}
\begin{block}{CRUD (4): Delete}
	\scriptsize
\begin{verbatim}
> db.students.deleteMany({"id":123})
{ "acknowledged" : true, "deletedCount" : 1 }

\end{verbatim}
\end{block}
\end{frame}

\section{基于pymongo的数据库连接}
\begin{frame}[t,fragile]{pymongo安装}
	\begin{block}{}
		\begin{itemize}
			\item via pip
\begin{verbatim}
$pip install pymongo
\end{verbatim}
			\item via distro (e.g., apt)
\begin{verbatim}
$sudo apt-get install python-pymongo
\end{verbatim}
		\end{itemize}
	\end{block}
\end{frame}

\begin{frame}[t,fragile]{pymongo API使用}
	\begin{block}{Python snippet}
		\scriptsize
\begin{verbatim}
import pymongo
from pymongo import MongoClient
client = MongoClient()

# Get the sampleDB database
db = client.sampleDB 
# equivalently, use db = client['sampleDB']
coll = db.sampleCollection
# equivalently, use coll = db['sampleCollection']
#CRUD: Create
coll.insert_one({"id": 123, "name": "zhangsan", "age": 18})
coll.insert_one({"id": 124, "name": "lisi", "age": 17})
#CRUD: Retrieve
for entry in coll.find():
    print("id: %d, name: %s, age: %d" % 
          (entry['id'], entry['name'], entry['age']))
\end{verbatim}
	\end{block}
\end{frame}

\begin{frame}[t,fragile]{pymongo API使用}
	\begin{block}{Python snippet}
		\scriptsize
\begin{verbatim}
#CRUD: Update
col.update({"age": {"$lt": 20}}, {"$inc": {"age": 1}})
#{u'n': 1, u'nModified': 1, u'ok': 1, 'updatedExisting': True}
col.update({"age": {"$lt": 20}}, {"$inc": {"age": 1}}, multi=True)
#{u'n': 2, u'nModified': 2, u'ok': 1, 'updatedExisting': True}
#CRUD: Delete
col.remove({"age": {"$gt": 10}})
#{u'n': 2, u'ok': 1}
coll.insert_one({"id": 123, "name": "zhangsan", "age": 18})
coll.insert_one({"id": 124, "name": "lisi", "age": 17})
col.remove({"age": {"$gt": 10}}, multi=False)
#{u'n': 1, u'ok': 1}
\end{verbatim}
	\end{block}
\end{frame}

\begin{frame}
	\vspace{3cm}
	\Huge
	Thanks
	\vspace{2cm}
	\normalsize
	\flushright
		Zhilei Ren

		zren@dlut.edu.cn
	
\end{frame}
\end{document}
